<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Order;
use Carbon\Carbon;
use App\Events\OrderPaid;
use App\Exceptions\InvalidRequestException;

class PaymentController extends Controller
{
    public function payByWechat(Order $order, Request $request) {
        // 校验权限
        $this->authorize('own', $order);
        // 校验订单状态
        if ($order->paid_at || $order->closed) {
            throw new InvalidRequestException('订单状态不正确');
        }

        $user = \Auth::user();

        //特殊用户微信1分钱测试
        $super_user = array('1');

        if($order->credit_num > $user->credit_score) {
            throw new InvalidRequestException('积分数量不正确，终止下单');
        } else {

            if(in_array($order->user->id, $super_user)) {
                $total_amount = 1;
            } else {
                $total_amount = (thToRmb($order->total_amount) - ($order->credit_num / 100)) * 100;
            }

            return app('wechat_pay')->mp([
                'out_trade_no' => $order->no,  // 商户订单流水号，与支付宝 out_trade_no 一样
                'total_fee' => $total_amount, // 与支付宝不同，微信支付的金额单位是分。
                'body'      => env('APP_NAME').'订单：'.$order->recharge_package->title, // 订单描述
                'openid' => $order->user->wx_open_id,
            ]);
        }
    }

    public function wechatNotify()
    {
        // 校验回调参数是否正确
        $data  = app('wechat_pay')->verify();
        // 找到对应的订单
        $order = Order::where('no', $data->out_trade_no)->first();
        // 订单不存在则告知微信支付
        if (!$order) {
            return 'fail';
        }
        // 订单已支付
        if ($order->paid_at) {
            // 告知微信支付此订单已处理
            return app('wechat_pay')->success();
        }

        // 将订单标记为已支付
        $order->update([
            'paid_at'        => Carbon::now(),
            'payment_method' => 'wechat_pay',
            'payment_no'     => $data->transaction_id,
            'is_pay'         => '1',
            'real_amount'    => $data->cash_fee
        ]);

        // 处理充值订单
        if($order->status == 1) {
            $this->afterPaid($order);
        }

        return app('wechat_pay')->success();
    }

    protected function afterPaid(Order $order)
    {
        event(new OrderPaid($order));
    }
}
